/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.EnumSet;

/**
 * <p>Project: smvc2022 - WebInit
 * <p>Powered by webrx On 2022-04-08 17:38:37
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class WebInit implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Create the 'root' Spring application context
        var rootContext = new AnnotationConfigWebApplicationContext();
        //(1)引入的spring IoC AppConfig.java 相当于　applicationContext.xml
        rootContext.register(SpringConfig.class);
        // Manage the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        var dispatcherContext = new AnnotationConfigWebApplicationContext();
        //(2)引入的springmvc WebInit.java 相当于　springmvc.xml
        dispatcherContext.register(SpringMvcConfig.class);

        // Register and map the dispatcher servlet
        var dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherContext){
            @Override
            protected void noHandlerFound(HttpServletRequest req, HttpServletResponse resp) throws Exception {
                //resp.sendRedirect("/static/404.html");
                req.getRequestDispatcher("/static/404.html").forward(req,resp);
            }
        });
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        //(3) spring 框架默认的编码过滤器 WebFilter 主要解决post提交，和 PrintWriter 输出乱码问题
        var csf = new CharacterEncodingFilter("utf-8");
        csf.setEncoding("utf-8");
        csf.setForceEncoding(true);
        csf.setForceResponseEncoding(true);
        csf.setForceResponseEncoding(true);
        var cf = servletContext.addFilter("cs", csf);
        cf.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), true, "/*");
    }
}
